const sha1 = require('sha1');
const redisCli = require('../../dbs/redisCli').client;
const createToken = require('../../utils/createToken');
const captcha = require('../../utils/captcha');
const cf = require('../../common_fn/commonFn');
const setCookie = require('../../utils/setCookie');
const checkParams = require('../../utils/checkParams');
const userModel = require('../../models/user');
const checkLogin = require('../../utils/checkLogin');

class Controller {
    async register(ctx,next){
        const ch = checkParams(['username','password'],ctx.request.body);
        if (!ch.status) {
            ctx.body = cf.dealMissArgsReq(ch.msg);
            return;
        }
        const {username,password} = ctx.request.body;
        let num = 0;
        await userModel.find({username:username}).count().then((n)=>{
            num = n;
        }).catch((err)=>{
            ctx.body =  cf.dealErrorReq(err);
            return;
        });
        if (num) {
            ctx.body = cf.dealErrorReq(`用户名"${username}"已存在！`);
            return;
        }
        const token = createToken(username);
        setCookie(ctx,'token',token);
        ctx.session[token] = username;
        const u = new userModel({
            username:username,
            password:password
        });
        await u.save().then((doc)=>{
            ctx.body = cf.dealSuccessReq(doc);
        }).catch((err)=>{
            ctx.body = cf.dealErrorReq(err);
        })
    }

    async getCaptcha(ctx,next){
        let rand = parseInt(Math.random()*2);
        let c = null;
        if (rand) {
            c = captcha.createRandCodeCaptcha();
        }else{
            c = captcha.createMathCaptcha();
        }
        await redisCli.set(ctx.request.ip,c.text);
        await redisCli.expire(ctx.request.ip,60);
        // ctx.response.type = 'image/svg+xml';
        ctx.body = cf.dealSuccessReq(c.data);
    }

    async login(ctx,next) {
        const ch = checkParams(['username','password','captchaCode'],ctx.request.body);
        if (!ch.status) {
            ctx.body = cf.dealMissArgsReq(ch.msg);
            return;
        }
        const {username,password,captchaCode} = ctx.request.body;
        let isCheckout = false;
        await redisCli.get(ctx.request.ip).then(async (data)=>{
            if (data) {
                if (`${data}`.toUpperCase()===`${captchaCode}`.toUpperCase()) {
                    isCheckout = true;
                    await redisCli.del(ctx.request.ip);
                }else{
                    ctx.body = cf.dealErrorReq('验证码错误！');
                }
            }else{
                ctx.body = cf.dealErrorReq('验证码过期！');
            }
        }).catch((err)=>{
            ctx.body = cf.dealErrorReq('验证码错误！');
        });
        if (!isCheckout) {
            return;
        }
        await userModel.findOne({username,password}).then((doc)=>{
            if (doc) {
                const token = createToken(username);
                setCookie(ctx,'token',token);
                ctx.session[token] = username;
                ctx.body = cf.dealSuccessReq(doc);
            }else{
                ctx.body = cf.dealNotFoundReq('用户名或密码错误！');
            }
        }).catch((err)=>{
            ctx.body = cf.dealErrorReq(err);
        })
    }
}

module.exports = new Controller();

